package org.ezplatform.office.forum.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.forum.dao.ForumIntegralDao;
import org.ezplatform.office.forum.entity.ForumIntegral;
import org.ezplatform.office.forum.entity.ForumIntegralRecord;
import org.ezplatform.office.forum.entity.ForumIntegralRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @desc 论坛积分Service
 * @create 2017-11-15 10:16
 **/
@Service
@Transactional
public class ForumIntegralService extends BaseService<ForumIntegral, String> {

    private final Logger log = LoggerFactory.getLogger(ForumIntegralService.class);
    
    @Autowired
    private ForumIntegralRuleService forumIntegralRuleService;
    
    @Autowired
    private ForumIntegralRecordService forumIntegralRecordService;
    
    @Autowired
    private ForumIntegralDao forumIntegralDao;
    
    @Autowired
	private LogService logService;
    
    @Override
    protected JpaBaseDao<ForumIntegral, String> getEntityDao() {
        return forumIntegralDao;
    }

	/**
	 * 获取论坛积分列表翻页数据
	 * @param localPageable
	 * @param localList
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public Page<Map> findByPage(Pageable pageable, List<PropertyFilter> propertyFilter){
		log.debug("<--------获取论坛积分列表翻页数据---->");
		StringBuilder sqlStr = new StringBuilder();
		Map<String, Object> paramMap = new HashMap<String, Object>(); 
		sqlStr.append("select t.id,t.useraccount,t.username,t.total_score from oa_forum_integral t where 1=1 ");	
		String sql = PropertyFilter.getSqlByFilterAndPageable("t", sqlStr.toString(), "t.createdDate desc",propertyFilter, pageable);		
		return super.findByPageNativeSQL(pageable, sql, paramMap);
	}
	
    /**
     * 扣减用户论坛积分
     * @param request
     * @return json
     */
	public OperationResult editPostIntegral(String[] ids,String editScore,String mark) {
		WebUser user = WebUtils.getCurrentUser();
		List<ForumIntegral> list = this.findAll(ids);
		for(ForumIntegral forumIntegral:list) {
			int totalScore = forumIntegral.getTotalScore();
			int score = Integer.parseInt(editScore);
			int totalScore_ = totalScore-score;
			if(totalScore_ < 0) {
				totalScore_ = 0;
			}
			forumIntegral.setTotalScore(totalScore_);
			forumIntegral.setMark(mark);
			this.save(forumIntegral);
			ForumIntegralRecord forumIntegralRecord = new ForumIntegralRecord();
			forumIntegralRecord.setUserid(forumIntegral.getUserid());
			forumIntegralRecord.setUseraccount(forumIntegral.getUseraccount());
			forumIntegralRecord.setUsername(forumIntegral.getUsername());
			forumIntegralRecord.setReduceAccount(user.getUserName());
			forumIntegralRecord.setReduceMark(mark);
			forumIntegralRecord.setReduceScore(score);
			forumIntegralRecord.setTotalScore(totalScore_);
			forumIntegralRecordService.editSave(forumIntegralRecord);
		}
		return OperationResult.buildSuccessResult();
	}

    /**
     * 根据userId获取用户论坛积分数据
     * @param userId
     * @return ForumIntegral
     */
    public ForumIntegral getIntegralViewInfo(String userId){
        return forumIntegralDao.getForumIntegral(userId);
	}
	
	/**
     * 用户论坛积分公共方法
     * @param request
     * @return json
     * 0-发帖，1-删帖，2-置顶，3-取消置顶，4-设置精华，5-取消精华，6-评论，7-删除评论，8-收藏，9-取消收藏
     * userId-积分用户id
     */
    @Async
	public void savePostIntegral(String userId,String userName,String userAccount,String postIntegralType) {
		//积分规则数据
		List<ForumIntegralRule> list = forumIntegralRuleService.getForumIntegralRule();
		ForumIntegralRule forumIntegralRule = null;
        if(list.size()>0) {
        	forumIntegralRule = list.get(0);
        }else {
        	forumIntegralRule = new ForumIntegralRule();
        }
        if("0".equals(postIntegralType)) {
        	//单日上限分
        	int dayScore = forumIntegralRule.getDayupScore();
        	int postScore = forumIntegralRule.getPostdelScore();
        	ForumIntegral forumIntegral= forumIntegralDao.getForumIntegral(userId);
        	if(forumIntegral!=null) {
        		//积分日期(毫秒数)+1天
        		long integralTime = new Date().getTime();
        		//最后积分日期
        		Date lastModifiedDate = forumIntegral.getLastModifiedDate();
        		long lastIntergraTime = 0;
        		if(lastModifiedDate!=null) {
        			lastIntergraTime = lastModifiedDate.getTime();
        		}else {
        			lastIntergraTime = forumIntegral.getCreatedDate().getTime();
        		}
        		long lastIntergraTime_ = lastIntergraTime + 86400000;//当日可积分日期
        		if(integralTime>lastIntergraTime_) {
        			forumIntegral.setDaychangeScore(0);
        		}
        		//单日总积分
        		int daychangeScore = forumIntegral.getDaychangeScore();
        		if(daychangeScore+postScore <= dayScore) {
        			forumIntegral.setPostScore(forumIntegral.getPostScore()+postScore);
        			forumIntegral.setTotalScore(postScore+forumIntegral.getTotalScore());
        			forumIntegral.setDaychangeScore(postScore+forumIntegral.getDaychangeScore());
        			this.save(forumIntegral);
        		}
        	}else {
        		ForumIntegral f = new ForumIntegral();
        		f.setUsername(userName);
        		f.setUseraccount(userAccount);
        		f.setUserid(userId);
        		//加分小于等于单日上限
        		if(postScore <= dayScore) {
        			f.setPostScore(postScore);
            		f.setTotalScore(postScore);
            		f.setDaychangeScore(postScore);
        		}else {
        			f.setPostScore(dayScore);
            		f.setTotalScore(dayScore);
            		f.setDaychangeScore(dayScore);
        		}
        		this.save(f);
        	}
        }else if("1".equals(postIntegralType)) {
        	int postScore = forumIntegralRule.getPostdelScore();
        	ForumIntegral forumIntegral= forumIntegralDao.getForumIntegral(userId);
        	if(forumIntegral!=null) {
        		int postScore_ = forumIntegral.getPostScore()-postScore;
        		if(postScore_<0) {
        			postScore_ = 0;
        		}
        		forumIntegral.setPostScore(postScore_);
        		forumIntegral.setTotalScore(forumIntegral.getTotalScore()-postScore < 0 ? 0 : forumIntegral.getTotalScore()-postScore);
        		forumIntegral.setDaychangeScore(forumIntegral.getDaychangeScore()-postScore < 0 ? 0 : forumIntegral.getDaychangeScore()-postScore);
        		this.save(forumIntegral);
        	}else {
        		ForumIntegral f = new ForumIntegral();
        		f.setUsername(userName);
        		f.setUseraccount(userAccount);
        		f.setUserid(userId);
        		f.setPostScore(0);
        		f.setTotalScore(0);
        		f.setDaychangeScore(0);
        		this.save(f);
        	}
        }else if("2".equals(postIntegralType)) {
        	//单日上限分
        	int dayScore = forumIntegralRule.getDayupScore();
        	int topdelScore=forumIntegralRule.getTopdelScore();
        	ForumIntegral forumIntegral= forumIntegralDao.getForumIntegral(userId);
        	if(forumIntegral!=null) {
        		//积分日期(毫秒数)+1天
        		long integralTime = new Date().getTime();
        		//最后积分日期
        		Date lastModifiedDate = forumIntegral.getLastModifiedDate();
        		long lastIntergraTime = 0;
        		if(lastModifiedDate!=null) {
        			lastIntergraTime = lastModifiedDate.getTime();
        		}else {
        			lastIntergraTime = forumIntegral.getCreatedDate().getTime();
        		}
        		long lastIntergraTime_ = lastIntergraTime + 86400000;//当日可积分日期
        		if(integralTime>lastIntergraTime_) {
        			forumIntegral.setDaychangeScore(0);
        		}
        		
        		//单日总积分
        		int daychangeScore = forumIntegral.getDaychangeScore();
        		if(daychangeScore+topdelScore <= dayScore) {
        			forumIntegral.setTopScore(forumIntegral.getTopScore()+topdelScore);
            		forumIntegral.setTotalScore(topdelScore+forumIntegral.getTotalScore());
        			forumIntegral.setDaychangeScore(topdelScore+forumIntegral.getDaychangeScore());
        			this.save(forumIntegral);
        		}
        	}else {
        		ForumIntegral f = new ForumIntegral();
        		f.setUsername(userName);
        		f.setUseraccount(userAccount);
        		f.setUserid(userId);
        		//加分小于等于单日上限
        		if(topdelScore <= dayScore) {
        			f.setTopScore(topdelScore);
            		f.setTotalScore(topdelScore);
            		f.setDaychangeScore(topdelScore);
        		}else {
        			f.setPostScore(dayScore);
            		f.setTotalScore(dayScore);
            		f.setDaychangeScore(dayScore);
        		}
        		this.save(f);
        	}
        }else if("3".equals(postIntegralType)) {
        	int topdelScore=forumIntegralRule.getTopdelScore();
        	ForumIntegral forumIntegral= forumIntegralDao.getForumIntegral(userId);
        	if(forumIntegral!=null) {
        		int topdelScore_ = forumIntegral.getTopScore()-topdelScore;
        		if(topdelScore_<0) {
        			topdelScore_ = 0;
        		}
        		forumIntegral.setTopScore(topdelScore_);
        		forumIntegral.setTotalScore(forumIntegral.getTotalScore()-topdelScore < 0 ? 0 : forumIntegral.getTotalScore()-topdelScore);
        		forumIntegral.setDaychangeScore(forumIntegral.getDaychangeScore()-topdelScore < 0 ? 0 : forumIntegral.getDaychangeScore()-topdelScore);
        		this.save(forumIntegral);
        	}else {
        		ForumIntegral f = new ForumIntegral();
        		f.setUsername(userName);
        		f.setUseraccount(userAccount);
        		f.setUserid(userId);
        		f.setTopScore(0);
        		f.setTotalScore(0);
        		f.setDaychangeScore(0);
        		this.save(f);
        	}
        }else if("4".equals(postIntegralType)) {
        	//单日上限分
        	int dayScore = forumIntegralRule.getDayupScore();
        	int essencedelScore=forumIntegralRule.getEssencedelScore();
        	ForumIntegral forumIntegral= forumIntegralDao.getForumIntegral(userId);
        	if(forumIntegral!=null) {
        		//积分日期(毫秒数)+1天
        		long integralTime = new Date().getTime();
        		//最后积分日期
        		Date lastModifiedDate = forumIntegral.getLastModifiedDate();
        		long lastIntergraTime = 0;
        		if(lastModifiedDate!=null) {
        			lastIntergraTime = lastModifiedDate.getTime();
        		}else {
        			lastIntergraTime = forumIntegral.getCreatedDate().getTime();
        		}
        		long lastIntergraTime_ = lastIntergraTime + 86400000;//当日可积分日期
        		if(integralTime>lastIntergraTime_) {
        			forumIntegral.setDaychangeScore(0);
        		}
        		//单日总积分
        		int daychangeScore = forumIntegral.getDaychangeScore();
        		if(daychangeScore+essencedelScore <= dayScore) {
        			forumIntegral.setEssenceScore(forumIntegral.getEssenceScore()+essencedelScore);
            		forumIntegral.setTotalScore(essencedelScore+forumIntegral.getTotalScore());
        			forumIntegral.setDaychangeScore(essencedelScore+forumIntegral.getDaychangeScore());
        			this.save(forumIntegral);
        		}
        	}else {
        		ForumIntegral f = new ForumIntegral();
        		f.setUsername(userName);
        		f.setUseraccount(userAccount);
        		f.setUserid(userId);
        		//加分小于等于单日上限
        		if(essencedelScore <= dayScore) {
        			f.setEssenceScore(essencedelScore);
            		f.setTotalScore(essencedelScore);
            		f.setDaychangeScore(essencedelScore);
        		}else {
        			f.setPostScore(dayScore);
            		f.setTotalScore(dayScore);
            		f.setDaychangeScore(dayScore);
        		}
        		this.save(f);
        	}
        }else if("5".equals(postIntegralType)) {
        	int essencedelScore=forumIntegralRule.getEssencedelScore();
        	ForumIntegral forumIntegral= forumIntegralDao.getForumIntegral(userId);
        	if(forumIntegral!=null) {
        		int essencedelScore_ = forumIntegral.getEssenceScore()-essencedelScore;
        		if(essencedelScore_<0) {
        			essencedelScore_ = 0;
        		}
        		forumIntegral.setEssenceScore(essencedelScore_);
        		forumIntegral.setTotalScore(forumIntegral.getTotalScore()-essencedelScore < 0 ? 0 : forumIntegral.getTotalScore()-essencedelScore);
        		forumIntegral.setDaychangeScore(forumIntegral.getDaychangeScore()-essencedelScore < 0 ? 0 : forumIntegral.getDaychangeScore()-essencedelScore);
        		this.save(forumIntegral);
        	}else {
        		ForumIntegral f = new ForumIntegral();
        		f.setUsername(userName);
        		f.setUseraccount(userAccount);
        		f.setUserid(userId);
        		f.setEssenceScore(0);
        		f.setTotalScore(0);
        		f.setDaychangeScore(0);
        		this.save(f);
        	}
        }else if("6".equals(postIntegralType)) {
        	//单日上限分
        	int dayScore = forumIntegralRule.getDayupScore();
        	int commentdelScore=forumIntegralRule.getCommentdelScore();
        	ForumIntegral forumIntegral= forumIntegralDao.getForumIntegral(userId);
        	if(forumIntegral!=null) {
        		//积分日期(毫秒数)+1天
        		long integralTime = new Date().getTime();
        		//最后积分日期
        		Date lastModifiedDate = forumIntegral.getLastModifiedDate();
        		long lastIntergraTime = 0;
        		if(lastModifiedDate!=null) {
        			lastIntergraTime = lastModifiedDate.getTime();
        		}else {
        			lastIntergraTime = forumIntegral.getCreatedDate().getTime();
        		}
        		long lastIntergraTime_ = lastIntergraTime + 86400000;//当日可积分日期
        		if(integralTime>lastIntergraTime_) {
        			forumIntegral.setDaychangeScore(0);
        		}
        		//单日总积分
        		int daychangeScore = forumIntegral.getDaychangeScore();
        		if(daychangeScore+commentdelScore <= dayScore) {
        			forumIntegral.setCommentScore(forumIntegral.getCommentScore()+commentdelScore);
            		forumIntegral.setTotalScore(commentdelScore+forumIntegral.getTotalScore());
        			forumIntegral.setDaychangeScore(commentdelScore+forumIntegral.getDaychangeScore());
        			this.save(forumIntegral);
        		}
        	}else {
        		ForumIntegral f = new ForumIntegral();
        		f.setUsername(userName);
        		f.setUseraccount(userAccount);
        		f.setUserid(userId);
        		//加分小于等于单日上限
        		if(commentdelScore <= dayScore) {
        			f.setCommentScore(commentdelScore);
            		f.setTotalScore(commentdelScore);
            		f.setDaychangeScore(commentdelScore);
        		}else {
        			f.setPostScore(dayScore);
            		f.setTotalScore(dayScore);
            		f.setDaychangeScore(dayScore);
        		}
        		this.save(f);
        	}
        }else if("7".equals(postIntegralType)) {
        	int commentdelScore=forumIntegralRule.getCommentdelScore();
        	ForumIntegral forumIntegral= forumIntegralDao.getForumIntegral(userId);
        	if(forumIntegral!=null) {
        		int commentdelScore_ = forumIntegral.getCommentScore()-commentdelScore;
        		if(commentdelScore_<0) {
        			commentdelScore_ = 0;
        		}
        		forumIntegral.setCommentScore(commentdelScore_);
        		forumIntegral.setTotalScore(forumIntegral.getTotalScore()-commentdelScore < 0 ? 0 : forumIntegral.getTotalScore()-commentdelScore);
        		forumIntegral.setDaychangeScore(forumIntegral.getDaychangeScore()-commentdelScore < 0 ? 0 : forumIntegral.getDaychangeScore()-commentdelScore);
        		this.save(forumIntegral);
        	}else {
        		ForumIntegral f = new ForumIntegral();
        		f.setUsername(userName);
        		f.setUseraccount(userAccount);
        		f.setUserid(userId);
        		f.setCommentScore(0);
        		f.setTotalScore(0);
        		f.setDaychangeScore(0);
        		this.save(f);
        	}
        }else if("8".equals(postIntegralType)) {
        	//单日上限分
        	int dayScore = forumIntegralRule.getDayupScore();
        	int favoritedelScore=forumIntegralRule.getFavoritedelScore();
        	ForumIntegral forumIntegral= forumIntegralDao.getForumIntegral(userId);
        	if(forumIntegral!=null) {
        		//积分日期(毫秒数)+1天
        		long integralTime = new Date().getTime();
        		//最后积分日期
        		Date lastModifiedDate = forumIntegral.getLastModifiedDate();
        		long lastIntergraTime = 0;
        		if(lastModifiedDate!=null) {
        			lastIntergraTime = lastModifiedDate.getTime();
        		}else {
        			lastIntergraTime = forumIntegral.getCreatedDate().getTime();
        		}
        		long lastIntergraTime_ = lastIntergraTime + 86400000;//当日可积分日期
        		if(integralTime>lastIntergraTime_) {
        			forumIntegral.setDaychangeScore(0);
        		}
        		//单日总积分
        		int daychangeScore = forumIntegral.getDaychangeScore();
        		if(daychangeScore+favoritedelScore <= dayScore) {
        			forumIntegral.setFavoriteScore(forumIntegral.getFavoriteScore()+favoritedelScore);
            		forumIntegral.setTotalScore(favoritedelScore+forumIntegral.getTotalScore());
        			forumIntegral.setDaychangeScore(favoritedelScore+forumIntegral.getDaychangeScore());
        			this.save(forumIntegral);
        		}
        	}else {
        		ForumIntegral f = new ForumIntegral();
        		f.setUsername(userName);
        		f.setUseraccount(userAccount);
        		f.setUserid(userId);
        		//加分小于等于单日上限
        		if(favoritedelScore <= dayScore) {
        			f.setFavoriteScore(favoritedelScore);
            		f.setTotalScore(favoritedelScore);
            		f.setDaychangeScore(favoritedelScore);
        		}else {
        			f.setPostScore(dayScore);
            		f.setTotalScore(dayScore);
            		f.setDaychangeScore(dayScore);
        		}
        		this.save(f);
        	}
        }else if("9".equals(postIntegralType)) {
        	int favoritedelScore=forumIntegralRule.getFavoritedelScore();
        	ForumIntegral forumIntegral= forumIntegralDao.getForumIntegral(userId);
        	if(forumIntegral!=null) {
        		int favoritedelScore_ = forumIntegral.getFavoriteScore()-favoritedelScore;
        		if(favoritedelScore_<0) {
        			favoritedelScore_ = 0;
        		}
        		forumIntegral.setFavoriteScore(favoritedelScore_);
        		forumIntegral.setTotalScore(forumIntegral.getTotalScore()-favoritedelScore < 0 ? 0 : forumIntegral.getTotalScore()-favoritedelScore);
        		forumIntegral.setDaychangeScore(forumIntegral.getDaychangeScore()-favoritedelScore < 0 ? 0 : forumIntegral.getDaychangeScore()-favoritedelScore);
        		this.save(forumIntegral);
        	}else {
        		ForumIntegral f = new ForumIntegral();
        		f.setUsername(userName);
        		f.setUseraccount(userAccount);
        		f.setUserid(userId);
        		f.setFavoriteScore(0);
        		f.setTotalScore(0);
        		f.setDaychangeScore(0);
        		this.save(f);
        	}
        }
	}
    
    /**
	    * 保存操作日志(异步请求)
	    * @param msgType
	    * @param corpId
	    * @param token
	    */
	  @Async
	  public void saveModuleLog(String code,String title,String value) {
		  logService.saveModuleLog(code, title, value);
	  }
	
}
